from fastapi import WebSocket
import json
from utils.log_util import logger

def generate_event(event_type: str, data: dict):
    return json.dumps({
        'event': event_type,
        'data': data
    })


class WSManager:
    def __init__(self):
        self.active_connections: dict[str, dict[str, WebSocket]] = {}

    async def connect(self, game_id: str, user_id: str, websocket: WebSocket):
        await websocket.accept()
        if game_id not in self.active_connections:
            self.active_connections[game_id] = {}
        self.active_connections[game_id][user_id] = websocket
        logger.info(f"User {user_id} joined game {game_id}")

    def disconnect(self, game_id: str, user_id: str):
        if game_id in self.active_connections and user_id in self.active_connections[game_id]:
            del self.active_connections[game_id][user_id]
            logger.info(f"User {user_id} left game {game_id}")
            if not self.active_connections[game_id]:
                del self.active_connections[game_id]
            logger.info(f"Game {game_id} is empty, removed from active connections")

    async def send_personal_message(self, game_id: str, user_id: str, message: str):
        if game_id in self.active_connections and user_id in self.active_connections[game_id]:
            await self.active_connections[game_id][user_id].send_text(message)

    async def broadcast(self, game_id: str, message: str):
        if game_id in self.active_connections:
            for user_id, connection in self.active_connections[game_id].items():
                await connection.send_text(message)

ws_manager = WSManager()